/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.common.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.koron.common.dfs.FastDFSClientWrapper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

@Component
public class DocConverterUtils2 {
    private static final Logger logger = LoggerFactory.getLogger(DocConverterUtils2.class);

    private static final String[] FILE_TYPE = new String[]{"doc", "docx", "xlsx", "xls", "pptx", "ppt"};

    @Value("${openoffice.host}")
    private String host;

    @Value("${openoffice.port}")
    private int port;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private FastFileStorageClient storageClient;

    @Value("${breakpoint.upload.dir}")
    private String defaultDir;


    public String converterUpdate(String fileUrl, String originalFileName) throws Exception {
        String temp = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
        String filePath = defaultDir + temp;
        File targetFile = converter(filePath, originalFileName);
        if (targetFile == null) {
            return null;
        }
        InputStream is = new FileInputStream(targetFile);
        String pdfPath = clientWrapper.uploadFile(is, targetFile.length(), FilenameUtils.getExtension(targetFile.getName()));
        is.close();
        if (targetFile.exists()) {
            targetFile.delete();
        }
        return pdfPath;
    }


    public File converter(String fileUrl, String originalFileName) {
        if (StringUtils.isBlank(fileUrl)) {
            return null;
        }
        String fileName = FilenameUtils.getBaseName(originalFileName);
        String sourceFileExtension = FilenameUtils.getExtension(originalFileName);
        if (!Arrays.asList(FILE_TYPE).contains(sourceFileExtension.toLowerCase())) {
            return null;
        }
        File sourceFile = new File(originalFileName);
        File targetFile;
        if ("xlsx".equals(sourceFileExtension) || "xls".equals(sourceFileExtension)) {
            targetFile = new File(fileName + ".html");
        } else {
            targetFile = new File(fileName + ".pdf");
        }
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
        try {
            //byte[] bytes = downloadFile(fileUrl);
            File inputFile = new File(fileUrl);
            if (!inputFile.exists()) {

                logger.info("源文件不存在！");
                return null;
            }
            connection.connect();
            //FileUtils.copyInputStreamToFile(new ByteArrayInputStream(bytes), sourceFile);
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, targetFile);
        } catch (Exception e) {
            logger.error("文件转换失败："+e.getMessage(),e);
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            //删除文件
            if (sourceFile.exists()) {
                sourceFile.delete();
            }
        }
        return targetFile;
    }


    public byte[] downloadFile(String fileUrl) throws IOException {
       /* String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);*/
        File file = new File(fileUrl);
        InputStream inStream = new FileInputStream(file);
        return new byte[inStream.available()];
    }


}
